package com.example.demo.controller;

import com.example.demo.demo.invoke.DialogueState;
import com.example.demo.enums.ActionType;
import com.example.demo.enums.CombinedAiResponseV2;
import com.example.demo.enums.NluResult;
import com.example.demo.enums.UserQuery;
import com.example.demo.model.dto.ai.AiDecision;
import com.example.demo.service.aiService.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;

@RestController
@RequestMapping("/ai")
public class LoveMasterController {

    private final NluService nluService;
    private final AdviceService adviceService;
    private final SessionService sessionService; // 注入我们的会话服务
    private final StreamingAiService streamingAiService;
    private final StreamingGenerationService streamingGenerationService;

    private final StateExtractionService stateExtractionService;
    private final DialoguePolicyService dialoguePolicyService;


    private static final Logger logger = LoggerFactory.getLogger(LoveMasterController.class);

    // --- 通用和 V2 (新架构) 所需的服务 ---
    private final UnifiedAiService unifiedAiService;

    // 更新构造函数，注入所有需要的服务
    public LoveMasterController(NluService nluService, AdviceService adviceService,
                                SessionService sessionService, StreamingAiService streamingAiService,
                                StreamingGenerationService streamingGenerationService, StateExtractionService stateExtractionService, DialoguePolicyService dialoguePolicyService, UnifiedAiService unifiedAiService) {
        this.nluService = nluService;
        this.adviceService = adviceService;
        this.sessionService = sessionService;
        this.streamingAiService = streamingAiService;
        this.streamingGenerationService = streamingGenerationService;
        this.stateExtractionService = stateExtractionService;
        this.dialoguePolicyService = dialoguePolicyService;
        this.unifiedAiService = unifiedAiService;
    }

    @PostMapping("/v1/advice")
    public String getLoveAdvice(@RequestBody UserQuery userQuery,
                                @RequestHeader("X-Session-ID") String sessionId) { // 从请求头获取 sessionId

        logger.info("Received request for sessionId: {}", sessionId);
        logger.info("User query: {}", userQuery.text());

        // --- DST 流程开始 ---

        // 1. 获取当前用户的对话状态（“病历”），无论新旧用户
        DialogueState currentState = sessionService.getState(sessionId);
        logger.info("State BEFORE update: {}", currentState);

        // 2. 对用户的【新】消息进行NLU分析
        NluResult nluResult = nluService.performNlu(userQuery.text());

        // 3. 用NLU结果【更新】当前对话状态
        currentState.updateState(nluResult);
        logger.info("State AFTER update: {}", currentState);

        // 4. 保存更新后的状态（对于内存实现是可选的，但对于Redis是必需的）
        sessionService.saveState(sessionId, currentState);

        // --- DST 流程结束 ---

        // 5. 将【完整且已更新的】对话状态，连同原始问题，一起传给建议生成服务
        // 注意：这里的 AdviceService 也需要改造，以接收 DialogueState 对象
        String advice = adviceService.generateAdvice(currentState, userQuery.text());

        return advice;
    }

    @PostMapping("/v2/advice")
    public String getLoveAdviceV2(@RequestBody UserQuery userQuery,
                                  @RequestHeader("X-Session-ID") String sessionId) {
        logger.info("[V2] Received request for sessionId: {}", sessionId);

        DialogueState currentState = sessionService.getState(sessionId);
        logger.info("[V2] State BEFORE processing: {}", currentState);

        // 调用统一服务，接收新的V2响应对象
        CombinedAiResponseV2 response = unifiedAiService.processTurn(currentState, userQuery.text());

        // 保存AI更新后的状态
        sessionService.saveState(sessionId, response.updatedState());
        logger.info("[V2] AI's internal thinking: {}", response.thinking()); // 我们可以打印出AI的思考过程，便于调试！
        logger.info("[V2] State AFTER processing: {}", response.updatedState());

        // 返回给用户的最终回复
        return response.replyToUser();
    }

    // --- V3 接口：新的、支持流式输出的方法 ---
    @PostMapping(value = "/v3/advice", produces = "text/event-stream")
    public SseEmitter getLoveAdviceV3(@RequestBody UserQuery userQuery,
                                      @RequestHeader("X-Session-ID") String sessionId) {
        logger.info("[V3] Received streaming request for sessionId: {}", sessionId);

        // 1. 创建一个 SseEmitter，设置一个较长的超时时间
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        // 2. 获取当前状态
        DialogueState currentState = sessionService.getState(sessionId);

        // 3. 【阶段一】执行快速的、非流式的决策调用
        AiDecision decision = streamingAiService.getAiDecision(currentState, userQuery.text());

        // 4. 立刻保存更新后的状态
        sessionService.saveState(sessionId, decision.updatedState());
        logger.info("[V3] AI Decision: {}, State Saved.", decision.action());

        // 5. 【阶段二】执行真正的、流式的生成调用
        Flux<String> replyStream = streamingAiService.streamReply(decision, userQuery.text());

        // 6. 订阅流，并将每个数据块通过 SseEmitter 发送给前端
        replyStream.subscribe(
                // onNext: 每次收到一小块文本时触发
                token -> {
                    try {
                        emitter.send(SseEmitter.event().data(token));
                    } catch (IOException e) {
                        logger.error("Error sending SSE event", e);
                        emitter.completeWithError(e);
                    }
                },
                // onError: 流处理出错时触发
                error -> {
                    logger.error("Error in AI stream", error);
                    emitter.completeWithError(error);
                },
                // onComplete: 流结束时触发
                () -> {
                    logger.info("[V3] Stream completed for sessionId: {}", sessionId);
                    emitter.complete();
                }
        );

        // 7. 立即返回 emitter 对象给Spring，建立长连接
        return emitter;
    }

    @PostMapping(value = "/v4/advice", produces = "text/event-stream")
    public SseEmitter getLoveAdvicev4(@RequestBody UserQuery userQuery,
                                      @RequestHeader("X-Session-ID") String sessionId) {
        logger.info("Received streaming request for sessionId: {}", sessionId);
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        try {
            // 1. 获取旧状态
            DialogueState currentState = sessionService.getState(sessionId);

            // 2. 【AI调用1】让AI更新状态
            DialogueState updatedState = stateExtractionService.updateState(currentState, userQuery.text());

            // 3. 【Java决策】由我们的策略服务决定下一步行动
            ActionType nextAction = dialoguePolicyService.decideNextAction(updatedState);
            logger.info("Java Policy Decision: {}", nextAction);

            // 4. 保存最新状态
            sessionService.saveState(sessionId, updatedState);

            // 5. 【AI调用2】让AI根据指令生成流式回复
            Flux<String> replyStream = streamingGenerationService.streamReply(updatedState, nextAction, userQuery.text());

            // 6. 订阅流并发送给前端
            replyStream.subscribe(
                    token -> {
                        try {
                            emitter.send(SseEmitter.event().data(token));
                        } catch (Exception e) {
                            logger.error("Error sending SSE event for sessionId: {}", sessionId, e);
                            emitter.completeWithError(e);
                        }
                    },
                    error -> {
                        logger.error("Error in AI stream for sessionId: {}", sessionId, error);
                        emitter.completeWithError(error);
                    },
                    () -> {
                        logger.info("Stream completed for sessionId: {}", sessionId);
                        emitter.complete();
                    }
            );
        } catch (Exception e) {
            logger.error("An error occurred while processing the request for sessionId: {}", sessionId, e);
            emitter.completeWithError(e);
        }

        return emitter;
    }
    // --- V2 接口：新的、二合一、高性能的方法 (新增) ---
//    @PostMapping("/v2/advice")
//    public String getLoveAdviceV2(@RequestBody UserQuery userQuery,
//                                  @RequestHeader("X-Session-ID") String sessionId) {
//        logger.info("[V2] Received request for sessionId: {}", sessionId);
//
//        // 1. 获取当前用户的对话状态
//        DialogueState currentState = sessionService.getState(sessionId);
//        logger.info("[V2] State BEFORE processing: {}", currentState);
//
//        // 2. 【一步到位】调用统一服务处理本轮对话
//        CombinedAiResponse response = unifiedAiService.processTurn(currentState, userQuery.text());
//
//        // 3. 保存AI返回的、已更新的对话状态
//        sessionService.saveState(sessionId, response.updatedState());
//        logger.info("[V2] State AFTER processing: {}", response.updatedState());
//
//        // 4. 将AI生成的回复直接返回给前端
//        return response.replyToUser();
//    }
}